<template>
  <div class="amap-page-container">
    <!--使用element UI作为输入框-->
    <el-amap
        vid="amapDemo"
        :center="this.mylnglat"
        :amap-manager="amapManager"
        :zoom="zoom"
        :events="events"
        class="amap-demo"
        style="height: 300px"
    >
      <el-amap-marker ref="marker" vid="component-marker" :position="mapInfo.lnglat"></el-amap-marker>
    </el-amap>
  </div>
</template>

<script>
import location from "@/plugins/positionLocation";
const amapManager = new AMapManager();
import { AMapManager } from 'vue-amap';
export default {
  name: "MyMap",
  props:['mylng','mylat'],
  data: function () {
    return {
      mapInfo: {
        //初始值
        lng: 113.605419,
        lat: 39.909187,
        lnglat: [113.605419, 34.739935]
      },
      zoom: 12,
      amapManager,
      events: {
        click: (e) => {
          this.mapInfo.lng = e.lnglat.lng;
          this.mapInfo.lat = e.lnglat.lat;
          this.mapInfo.lnglat = [e.lnglat.lng, e.lnglat.lat];
          this.getFormattedAddress();
        }
      }
    };
  },
  methods: {
    getFormattedAddress() {
      AMap.plugin('AMap.Geocoder', () => {
        let GeocoderOptions = {
          city: '全国'
        };
        let geocoder = new AMap.Geocoder(GeocoderOptions);
        geocoder.getAddress(this.mapInfo.lnglat, (status, result) => {
          this.$emit("getMapInfo",this.mapInfo.lnglat);
          if (status === 'complete' && result.info === 'OK') {
            this.mapInfo.address = result.regeocode.formattedAddress;
          } else {
            this.mapInfo.address = '无法获取地址';
          }
        });
      });
    },
    initMapByInput() {
      AMap.plugin('AMap.Autocomplete', () => {
        let autoOptions = {
          city: '全国',
          input: 'tipinput'
        };
        let autoComplete = new AMap.Autocomplete(autoOptions);
        AMap.event.addListener(autoComplete, 'select', (e) => {
          console.log('通过输入拿到的地址', e);
          this.mapInfo.lat = e.poi.location.lat;
          this.mapInfo.lng = e.poi.location.lng;
          this.mapInfo.lnglat = [e.poi.location.lng, e.poi.location.lat];
          this.getFormattedAddress();
        });
      });
    },
    getLocation() {
      let flag = this
      let geolocation = location.initMap('map-container') // 定位
      AMap.event.addListener(geolocation, 'complete', result => {
        flag.mapInfo.lnglat=[result.position.lng,result.position.lat]
        flag.mapInfo.address=result.formattedAddress
      })
    },
  },
  computed:{
   mylnglat:{
     get(){
       if (this.mylng===undefined||this.mylat===undefined){
         this.mapInfo.lnglat=[113.605419, 34.739935]
         return [113.605419, 34.739935]
       }else {
         this.mapInfo.lnglat=[this.mylng,this.mylat]
         return [this.mylng,this.mylat]
       }
     }
   }
  },
  mounted() {
    this.initMapByInput();
  }
}
</script>

<style scoped>
.amap-demo {
  height: 300px;
}
</style>